package com.tql.pandian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.utils.CalculatedValueUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.tql.pandian.entity.*;
import com.tql.pandian.entity.dto.*;
import com.tql.pandian.entity.vo.BomListVo;
import com.tql.pandian.entity.vo.PanDianDataCaseVo;
import com.tql.pandian.entity.vo.PanDianDataVo;
import com.tql.pandian.entity.vo.PandianCaseStapVo;
import com.tql.pandian.event.LogEvent;
import com.tql.pandian.mapper.*;
import com.tql.pandian.service.IPandianDataService;
import com.tql.pandian.service.IStapInChangeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PandianDataService implements IPandianDataService {

    @Autowired
    private PandianDataMapper pandianDataMapper;

    @Autowired
    private TqlPandianCaseMapper tqlPandianCaseMapper;

    @Autowired
    private PandianPeriodMapper pandianPeriodMapper;

    @Autowired
    private PandianPeriodShopMapper pandianPeriodShopMapper;

    @Autowired
    private TqlPandianDataCaseMapper tqlPandianDataCaseMapper;

    @Autowired
    private TqlPandianDataLogMapper tqlPandianDataLogMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private IStapInChangeService stapInChangeService;

    @Override
    public List<PanDianDataVo> getPanDianData(PanDianDataDTO panDianDataDTO) {
        return pandianDataMapper.selectPanDianDataList(panDianDataDTO);
    }


    private ResultDTO cratePanDianData2(PianDianDataListDTO createPanDianDataDTO)
    {
        //系统自带参数
        String deptCode = SecurityUtils.getLoginUser().getSysUser().getDeptCode();
        Long creator=SecurityUtils.getUserId();
        String creater=SecurityUtils.getUsername();
        //后端提供参数
        String pandianCode=createPanDianDataDTO.getPandianCode();
        Long caseId=createPanDianDataDTO.getCaseId();
        Long pid=createPanDianDataDTO.getPid();
        Integer semiType=createPanDianDataDTO.getSemiType();
        String stapCode=createPanDianDataDTO.getStapCode();
        String stapName= createPanDianDataDTO.getStapName();
        BigDecimal stapAmout=createPanDianDataDTO.getStapAmout();
        String stapBaseUnit=createPanDianDataDTO.getStapBaseUnit();
        int flag=createPanDianDataDTO.getFlag();

        Date date=new Date();
        TqlPandianDataLogEntity dataLog =getPandianLog(pandianCode,creater,creator,caseId,pid,deptCode);

        List<PandianDataEntity> stapList =new   ArrayList<PandianDataEntity>();
        List<TqlPandianDataCaseEntity> semiStapList=new   ArrayList<TqlPandianDataCaseEntity>();

        if((semiType==0&&flag==0)||(semiType==1&&flag==0))//插入
        {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String result = uuid.substring(0, Math.min(uuid.length(), 30));
            String semi=semiType == 0?null:result;

                PandianDataEntity vo = getPandianData(pid, caseId, creator, stapCode, stapName, stapAmout,stapBaseUnit , deptCode, creater, date, pandianCode,semi);
                stapList.add(vo);

               // PandianDataEntity vo = getPandianData(pid, caseId, creator, stapCode, stapName, stapAmout,stapBaseUnit , deptCode, creater, date, pandianCode,semi);
              if(semiType==1) {
                  //查询到当前半成品对应的bom信息
                  List<BomListVo> semiFood = pandianDataMapper.selectBomLists(Long.parseLong(stapCode));
                  //变成盘点数据
                  List<TqlPandianDataCaseEntity> semiList = getSemiPandian(semiFood, pid + "", creater, creator, caseId + "", date, stapAmout, pandianCode,semi);
                  if (!CollectionUtils.isEmpty(semiList)) semiStapList.addAll(semiList);
              }

            insertPandianLogAndPandianData(dataLog,stapList,semiStapList);
        }

        if((semiType==0&&flag==1)||(semiType==1&&flag==1))//修改
        {

               PandianDataEntity vo =new PandianDataEntity(createPanDianDataDTO.getId(), createPanDianDataDTO.getStapAmout());
            PandianDataEntity dto= pandianDataMapper.selectById(createPanDianDataDTO.getId());
            String semi=dto.getSemi();
                //查询到当前半成品对应的bom信息
                List<BomListVo> semiFood = pandianDataMapper.selectBomLists(Long.parseLong(stapCode));
                //变成盘点数据
                List<TqlPandianDataCaseEntity> semiList = getSemiPandian(semiFood, pid+"", creater,creator, caseId+"", date, stapAmout, pandianCode,semi);
                if(!CollectionUtils.isEmpty(semiList))  semiStapList.addAll(semiList);

               updatePandianLogAndPandianData(dataLog,vo,semiStapList);
        }







//
//        if (semiType == 0 ) {
//            PandianDataEntity vo = getPandianData(pid, caseId, creator, stapCode, stapName, stapAmout,stapBaseUnit , deptCode, creater, date, pandianCode);
//            stapList.add(vo);
//        } else {
//            //查询到当前半成品对应的bom信息
//            List<BomListVo> semiFood = pandianDataMapper.selectBomLists(Long.parseLong(stapCode));
//            //变成盘点数据
//            List<TqlPandianDataCaseEntity> semiList = getSemiPandian(semiFood, pid+"", creater,creator, caseId+"", date, stapAmout, pandianCode);
//            if(!CollectionUtils.isEmpty(semiList))  semiStapList.addAll(semiList);
//        }
//
//
//    insertPandianLogAndPandianData(dataLog,stapList,semiStapList);



        applicationContext.publishEvent(new LogEvent(dataLog));
        return ResultDTO.success(1,200,"创建盘点单成功");

    }




   void  updatePandianLogAndPandianData( TqlPandianDataLogEntity dataLog, PandianDataEntity vo,     List<TqlPandianDataCaseEntity> semiList)
   {
       tqlPandianDataLogMapper.insert(dataLog);

           vo.setCaseAmount(vo.getStapAmout());
           int result = pandianDataMapper.updateById(vo);


       if(!CollectionUtils.isEmpty(semiList))
       {
           tqlPandianDataCaseMapper.deleteDataCase(vo.getId());
           tqlPandianDataCaseMapper.batchPanDianDataCaseInsert(semiList);
       }

   }


    @Override
    public ResultDTO createPanDianData(PianDianDataListDTO dto) {
      //  PianDianDataListDTO dto=createPanDianDataDTO.getPandianData();
                return cratePanDianData2(dto);

    }

    private ResultDTO cratePanDianData1(CreatePanDianDataDTO createPanDianDataDTO) {

        String deptCode = SecurityUtils.getLoginUser().getSysUser().getDeptCode();
        Long creator=SecurityUtils.getUserId();
        String creater=SecurityUtils.getUsername();
        String pandianCode=createPanDianDataDTO.getPandianCode();
        String caseId=createPanDianDataDTO.getCaseId();
        String pid=createPanDianDataDTO.getPid();
        Date date=new Date();
        List<PianDianDataListDTO>  pandianStapList=createPanDianDataDTO.getPianDianDataListDTOList();
        //这里新增了pandianCode
        TqlPandianDataLogEntity dataLog =getPandianLog(pandianCode,creater,creator,Long.parseLong(caseId),Long.parseLong(pid),deptCode);
        List<PandianDataEntity> stapList =new   ArrayList<PandianDataEntity>();
        List<TqlPandianDataCaseEntity> semiStapList=new   ArrayList<TqlPandianDataCaseEntity>();
        if(!CollectionUtils.isEmpty(pandianStapList)) {
            for (PianDianDataListDTO m : pandianStapList) {
                //0物料 1半成品
                int semiType = m.getSemiType();
                if (semiType == 0) {
                    PandianDataEntity vo = getPandianData(Long.parseLong(pid), Long.parseLong(caseId), creator, m.getStapCode(), m.getStapName(), m.getStapAmout(), m.getStapBaseUnit(), deptCode, creater, date, pandianCode,null);
                    stapList.add(vo);


                } else {
                    //查询到当前半成品对应的bom信息
                    List<BomListVo> semiFood = pandianDataMapper.selectBomLists(Long.parseLong(m.getStapCode()));
                    //变成盘点数据
                    List<TqlPandianDataCaseEntity> semiList = getSemiPandian(semiFood, pid, creater,creator, caseId, date, m.getStapAmout(), pandianCode,null);
                    if(!CollectionUtils.isEmpty(semiList))  semiStapList.addAll(semiList);
                }
            }
        }

        insertPandianLogAndPandianData(dataLog,stapList,semiStapList);

        applicationContext.publishEvent(new LogEvent(dataLog));
        return ResultDTO.success(1,200,"创建盘点单成功");

        /************先判断入库表中是否存在物料*************/
        //  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        StringBuffer messageContent = new StringBuffer();
//        //获取店铺编码
//        String deptCode = SecurityUtils.getLoginUser().getSysUser().getDeptCode();
//        Long creator=SecurityUtils.getUserId();
//        String creater=SecurityUtils.getUsername();
        //记录日志
//        TqlPandianDataLogEntity dataLog = new TqlPandianDataLogEntity();




//        QueryWrapper<TqlPandianDataCaseEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq("pid",createPanDianDataDTO.getPid());
//        wrapper.eq("case_id",createPanDianDataDTO.getCaseId());
//        List<TqlPandianDataCaseEntity> pandianDataEntityList = tqlPandianDataCaseMapper.selectList(wrapper);
//        if (pandianDataEntityList.size() > 0){
//            applicationContext.publishEvent(new LogEvent(dataLog));
//            dataLog.setDataContent("创建盘点单失败，盘点单已创建过了");
//            tqlPandianDataLogMapper.insert(dataLog);
//            return ResultDTO.success(0,700,"创建盘点单失败，盘点单已创建了");
//        }
        /************插入盘点tql_pandian_data_case (办成品未打散)*************/
//        List<TqlPandianDataCaseEntity> dataCaseList = createPanDianDataDTO.getPianDianDataListDTOList().stream().map(m->{
//            TqlPandianDataCaseEntity vo = new TqlPandianDataCaseEntity();
//            vo.setPid(Long.parseLong(createPanDianDataDTO.getPid()));
//            vo.setCaseId(Long.parseLong(createPanDianDataDTO.getCaseId()));
//            vo.setSemiType(m.getSemiType());
//            vo.setStapCode(m.getStapCode());
//            vo.setStapName(m.getStapName());
//            vo.setStapAmout(m.getStapAmout());
//            vo.setStapBaseUnit(m.getStapBaseUnit());
//            vo.setDeptCode(createPanDianDataDTO.getDeptCode());
//            vo.setCreateBy(SecurityUtils.getUsername());
//            vo.setCreateTime(new Date());
//            return vo;
//        }).collect(Collectors.toList());

        /************插入盘点tql_pandian_data (存在半成品物料打散)*************/
//        List<PandianDataEntity> list  = new ArrayList<>();
//        createPanDianDataDTO.getPianDianDataListDTOList().forEach(t->{
//            PandianDataEntity entity = new PandianDataEntity();
//            entity.setPid(Long.parseLong(createPanDianDataDTO.getPid()));
//            entity.setCaseId(Long.parseLong(createPanDianDataDTO.getCaseId()));
//            entity.setDeptCode(createPanDianDataDTO.getDeptCode());
//            entity.setDel(0);
//            entity.setCreator(SecurityUtils.getUserId());
//            entity.setCreateBy(SecurityUtils.getUsername());
//            entity.setCreateTime(new Date());
//
//            //店铺编码+班组编码+时间段月份+时间段序号
//            entity.setCode(createPanDianDataDTO.getPandianCode());
//            //entity.setCode(deptCode+createPanDianDataDTO.getDeptCode()+createPanDianDataDTO.getMouthDay()+createPanDianDataDTO.getSeq());
//            if (t.getSemiType().equals(1)){
//                List<BomListVo> maps = pandianDataMapper.selectBomLists(Long.parseLong(t.getStapCode()));
//                if (!CollectionUtils.isEmpty(maps)){
//                    List<PandianDataEntity> aa = maps.stream().map(l->{
//                        PandianDataEntity b = new PandianDataEntity();
//                        b.setPid(Long.parseLong(createPanDianDataDTO.getPid()));
//                        b.setCaseId(Long.parseLong(createPanDianDataDTO.getCaseId()));
//                        b.setDel(0);
//                        b.setCreator(SecurityUtils.getUserId());
//                        b.setCreateBy(SecurityUtils.getUsername());
//                        b.setCreateTime(new Date());
//                        //店铺编码+班组编码+时间段月份+时间段序号
//                        b.setCode(createPanDianDataDTO.getPandianCode());
//                        //b.setCode(deptCode+createPanDianDataDTO.getDeptCode()+createPanDianDataDTO.getMouthDay()+createPanDianDataDTO.getSeq());
//                        /*b.setStapAmout(t.getStapAmout().multiply(new BigDecimal(l.get("quota").toString())));
//                        b.setStapName((String) l.get("stap_name"));
//                        b.setStapCode((String) l.get("stap_code"));*/
//                        b.setStapAmout(CalculatedValueUtil.multiplyB(t.getStapAmout(),l.getQuota()));
//                        b.setStapName(l.getStapName());
//                        b.setStapCode(l.getStapCode());
//                        b.setDeptCode(createPanDianDataDTO.getDeptCode());
//                        b.setStapBaseUnit(l.getUnit());
//                        String stapPrice = tqlPandianDataCaseMapper.selectStapPrice(l.getStapCode());
//                        if (StringUtils.isEmpty(stapPrice)){
//                            b.setStapPrice(new BigDecimal(0));
//                        }else {
//                            b.setStapPrice(new BigDecimal(stapPrice));
//                        }
//                        /******校验盘点物料是否在库存中**************/
//                        StapCountBoolDTO dto = new StapCountBoolDTO();
//          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                        dto.setNowDay(sdf.format(new Date()));
//                        dto.setStapCode(l.getStapCode());
//                        int kk = stapInChangeService.selectStapCountBool(dto);
//                        if (kk==0){
//                            messageContent.append("半成品："+t.getStapName()+"-物料"+l.getStapName()+",暂无该物料库存");
//                        }
//                        return b;
//                    }).collect(Collectors.toList());
//                    list.addAll(aa);
//                }
//            }else {
//                entity.setStapAmout(t.getStapAmout());
//                entity.setStapBaseUnit(t.getStapBaseUnit());
//                entity.setStapName(t.getStapName());
//                entity.setStapCode(t.getStapCode());
//                String stapPrice = tqlPandianDataCaseMapper.selectStapPrice(t.getStapCode());
//                if (StringUtils.isEmpty(stapPrice)){
//                    entity.setStapPrice(new BigDecimal(0));
//                }else {
//                    entity.setStapPrice(new BigDecimal(stapPrice));
//                }
//                list.add(entity);
//
//                /******校验盘点物料是否在库存中**************/
//                StapCountBoolDTO dto = new StapCountBoolDTO();
//                dto.setNowDay(sdf.format(new Date()));
//                dto.setStapCode(t.getStapCode());
//                int kk= stapInChangeService.selectStapCountBool(dto);
//                if (kk==0){
//                    messageContent.append("物料："+t.getStapName()+",暂无该库存。");
//                }
//            }
//        });
//        if (messageContent.toString().length() > 0){
//            log.info("校验物料信息：{}",messageContent);
//            //发出一个监听事件

//            dataLog.setDataContent("创建盘点单失败，"+messageContent.toString());
//            tqlPandianDataLogMapper.insert(dataLog);
//            return ResultDTO.success(0,500,"创建盘点单失败："+messageContent.toString());
//        }
//        //插入盘点单 tql_pandian_data (打散，与未打散的表中) 表中
//        int w = tqlPandianDataCaseMapper.batchPanDianDataCaseInsert(dataCaseList);
//        int y = pandianDataMapper.batchInsertPanDianData(list);
//        tqlPandianDataLogMapper.insert(dataLog);
    }

    @Transactional
    private void insertPandianLogAndPandianData(TqlPandianDataLogEntity dataLog, List<PandianDataEntity> stapList, List<TqlPandianDataCaseEntity> semiStapList) {

        tqlPandianDataLogMapper.insert(dataLog);
        if(!CollectionUtils.isEmpty(stapList))
        pandianDataMapper.batchInsertPanDianData(stapList);
        if(!CollectionUtils.isEmpty(semiStapList))
        tqlPandianDataCaseMapper.batchPanDianDataCaseInsert(semiStapList);
//        tqlPandianDataCaseMapper.batchSemiPanDianDataCaseInsert(semiStapList);
    }

    /**
     *
     * @param semiFood
     * @param pid
     * @param creater
     * @param caseId
     * @param date
     * @param amount
     * @return
     */
    private List<TqlPandianDataCaseEntity> getSemiPandian(List<BomListVo> semiFood,String pid,String creater,Long creator,String caseId,Date date,BigDecimal amount,String pandianCode,String semi) {
        if(CollectionUtils.isEmpty(semiFood))return null;
        List<TqlPandianDataCaseEntity> list=new ArrayList<TqlPandianDataCaseEntity>();
        semiFood.stream().forEach(e->{

            BigDecimal quota= e.getQuota();
            String stapCode= e.getStapCode();
            String stapName=e.getStapName();
            String unit= e.getUnit();
//            String deptName=e.getDeptName();
            String deptCode1=e.getDeptCode();
            BigDecimal sum= CalculatedValueUtil.multiplyB(amount,quota);
            TqlPandianDataCaseEntity vo =getPandianDataCase(Long.parseLong(pid),Long.parseLong(caseId),creator,stapCode,stapName,sum,unit,deptCode1,creater,date,pandianCode,semi);
            list.add(vo);
        });
        return list;
    }

    private TqlPandianDataCaseEntity getPandianDataCase(long pid, long caseId, Long creator, String stapCode, String stapName, BigDecimal sum, String unit, String deptCode1, String creater, Date date, String pandianCode,String semi) {
        TqlPandianDataCaseEntity vo=new TqlPandianDataCaseEntity();
        vo.setPid(pid);
        vo.setCaseId(caseId);
        vo.setStapCode(stapCode);
        vo.setStapName(stapName);
        vo.setStapAmout(sum);
        vo.setStapBaseUnit(unit);
        vo.setDeptCode(deptCode1);
        vo.setCreateBy(creater);
        vo.setSemi(semi);
        vo.setCreateTime(date);
        vo.setPandianCode(pandianCode);
        return vo;




    }

    /**
     *    private Long id;
     *     private Long pid;
     *     private Long caseId;
     *     private String stapCode;
     *     private BigDecimal stapAmout;
     *     private String deptCode;
     *     private String stapBaseUnit;
     *     private BigDecimal stapPrice;
     *     private Integer del;
     *     private Long creator;
     *     private String createBy;
     *     private Date createTime;
     *     private String code;
     *     private String stapName;
     * @param pid
     * @param caseId
     * @param creator
     * @param stapCode
     * @param stapName
     * @param stapAmout
     * @param stapBaseUnit
     * @param deptCode
     * @param creater
     * @param date
     * @param pandianCode
     * @return
     */
    private PandianDataEntity getPandianData(long pid, long caseId, Long creator, String stapCode, String stapName, BigDecimal stapAmout, String stapBaseUnit, String deptCode, String creater, Date date,String pandianCode,String semi) {
        PandianDataEntity vo=new PandianDataEntity();
        vo.setPid(pid);
        vo.setCaseId(caseId);
        vo.setStapCode(stapCode);
        vo.setStapName(stapName);
        vo.setStapAmout(stapAmout);
        vo.setStapBaseUnit(stapBaseUnit);
        vo.setCaseAmount(stapAmout);
        vo.setCaseUnit(stapBaseUnit);
        vo.setDeptCode(deptCode);
        vo.setCreateBy(creater);
        vo.setCreator(creator);
        vo.setCreateTime(date);
        vo.setCode(pandianCode);
        vo.setSemi(semi);
        BigDecimal stapPrice=tqlPandianCaseMapper.getPriceByStapCodeAndDeptCode(stapCode,deptCode);
        vo.setStapPrice(stapPrice);
    return vo;
    }

    /**
     *
     * @param pandianCode 盘点编码
     * @param creater 创建人姓名
     * @param creator 创建人主键
     * @param caseId 仓库ID
     * @param pid 创建人信息
     * @param deptCode 班组编码
     * @return
     */
    private TqlPandianDataLogEntity getPandianLog(String pandianCode,String creater,Long creator,Long caseId,Long pid,String deptCode) {
        TqlPandianDataLogEntity dataLog=new TqlPandianDataLogEntity();
        dataLog.setDataType(1);
        dataLog.setDataContent(creater);
        dataLog.setCaseId(caseId);
        dataLog.setPid(pid);
        dataLog.setDeptCode(deptCode);
        dataLog.setCreator(creator);
        dataLog.setCreateBy(creater);
        dataLog.setCreateTime(new Date());
        dataLog.setPandianCode(pandianCode);
        return dataLog;
    }
    @Override
    public CaseStapAndMaterialTransUnit getStapInfoByStapCode(UpdatePanDianDataData dto) {

    Integer semiType=dto.getSemiType();
        CaseStapAndMaterialTransUnit cs=null;
if(0==semiType)
{
     cs=tqlPandianCaseMapper.selectStapByStapCode(dto.getStapCode());
     cs.setSemiType("0");
}
else {

     cs=tqlPandianCaseMapper.selectStapByStapCode1(dto.getStapCode());
    cs.setSemiType("1");
}

//        CaseStapAndMaterialTransUnit cs1= tqlPandianCaseMapper.selectCaseStapByStapCode(dto);
//        if(!Objects.isNull(cs1))
//        cs.setSemiType(semiType);
        CaseStapAndMaterialTransUnit cs2=tqlPandianCaseMapper.getPandianData(dto);
        if(!Objects.isNull(cs2)) {
            cs.setCaseAmount(null==cs2.getCaseAmount()?null:cs2.getCaseAmount());
            cs.setStapAmout(null==cs2.getStapAmout()?null:cs2.getStapAmout());
            cs.setCaseUnit(null==cs2.getCaseUnit()?null:cs2.getCaseUnit());
            cs.setFlag(1);
            cs.setId(cs2.getId());
        }
        else {
            cs.setFlag(0);
        }
        return cs;
    }
    @Override
    public PanDianDataCaseVo getPanDianDataById(UpdatePanDianDataData dto) {
        PanDianDataCaseVo panDianDataCaseVo = new PanDianDataCaseVo();
        panDianDataCaseVo.setPanDianCase(tqlPandianCaseMapper.selectById(dto.getCaseId()));
        PanDianPeriodShopEntity panDianPeriodShop = pandianPeriodShopMapper.selectPeriodShopById(dto.getPid());
        panDianDataCaseVo.setPandianPeriodShop(panDianPeriodShop);
        panDianDataCaseVo.setTqlPandianPeriod(pandianPeriodMapper.selectPeriodById(Long.valueOf(panDianPeriodShop.getPid())));
//        QueryWrapper<TqlPandianDataCaseEntity> dataCaseWarpper = new QueryWrapper<>();
//        dataCaseWarpper.eq("pid",dto.getPid());
//        dataCaseWarpper.eq("case_id",dto.getCaseId());
//        List<TqlPandianDataCaseEntity> dataCaseList = tqlPandianDataCaseMapper.selectList(dataCaseWarpper);
//        if (dataCaseList.size() > 0){
//            List<PandianCaseStapVo> pandianCaseStapVoList = dataCaseList.stream().map(t->{
//                PandianCaseStapVo k = new PandianCaseStapVo();
//                k.setId(String.valueOf(t.getId()));
//                k.setCaseId(String.valueOf(t.getCaseId()));
//                k.setStapCode(t.getStapCode());
//                k.setStapName(t.getStapName());
//                k.setSemiType(t.getSemiType());
//                k.setStapAmout(t.getStapAmout());
//                k.setStapBaseUnit(t.getStapBaseUnit());
//                return k;
//            }).collect(Collectors.toList());
//            panDianDataCaseVo.setPanDianCaseStapList(pandianCaseStapVoList);
//            panDianDataCaseVo.setDataCaseIds(pandianCaseStapVoList.stream().map(e-> e.getId()).collect(Collectors.toList()));
//        }
        QueryWrapper<PandianDataEntity> dataWarpper = new QueryWrapper<>();
        dataWarpper.eq("pid",dto.getPid());
        dataWarpper.eq("case_id",dto.getCaseId());
        List<PandianDataEntity> bb = pandianDataMapper.selectList(dataWarpper);
        List<String> ids = bb.stream().map(e-> e.getId().toString()).collect(Collectors.toList());
        panDianDataCaseVo.setIds(ids);
        panDianDataCaseVo.setPandianData(bb);
        return panDianDataCaseVo;
    }

    @Override
    public ResultDTO updatePanDianData(CreatePanDianDataDTO createPanDianDataDTO) {

        TqlPandianDataLogEntity dataLog = new TqlPandianDataLogEntity();
        dataLog.setDataType(2);
        dataLog.setDataContent("修改盘点单物料"+
                createPanDianDataDTO.getPianDianDataListDTOList().stream().
                        map(h->h.getStapName() +"-"+ h.getStapAmout()).collect(Collectors.joining(",")));
        dataLog.setCaseId(Long.parseLong(createPanDianDataDTO.getCaseId()));
        dataLog.setPid(Long.parseLong(createPanDianDataDTO.getPid()));
        dataLog.setDeptCode(SecurityUtils.getLoginUser().getSysUser().getDeptCode());
        dataLog.setCreator(SecurityUtils.getUserId());
        dataLog.setCreateBy(SecurityUtils.getUsername());
        dataLog.setCreateTime(new Date());

        /************先判断入库表中是否存在物料*************/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        StringBuffer messageContent = new StringBuffer();

        List<TqlPandianDataCaseEntity> dataCaseList = createPanDianDataDTO.getPianDianDataListDTOList().stream().map(m->{
            TqlPandianDataCaseEntity vo = new TqlPandianDataCaseEntity();
            vo.setPid(Long.parseLong(createPanDianDataDTO.getPid()));
            vo.setCaseId(Long.parseLong(createPanDianDataDTO.getCaseId()));
            vo.setSemiType(m.getSemiType());
            vo.setStapCode(m.getStapCode());
            vo.setStapName(m.getStapName());
            vo.setStapAmout(m.getStapAmout());
            vo.setStapBaseUnit(m.getStapBaseUnit());
            vo.setDeptCode(createPanDianDataDTO.getDeptCode());
            vo.setCreateBy(SecurityUtils.getUsername());
            vo.setCreateTime(new Date());
            return vo;
        }).collect(Collectors.toList());

        /************操作tql_pandian_data (存在半成品物料打散)*************/
        List<PandianDataEntity> list  = new ArrayList<>();
        createPanDianDataDTO.getPianDianDataListDTOList().forEach(t->{
            PandianDataEntity entity = new PandianDataEntity();
            entity.setPid(Long.parseLong(createPanDianDataDTO.getPid()));
            entity.setCaseId(Long.parseLong(createPanDianDataDTO.getCaseId()));
            entity.setDel(0);
            entity.setCreator(SecurityUtils.getUserId());
            entity.setCreateBy(SecurityUtils.getUsername());
            entity.setCreateTime(new Date());
            //获取店铺编码
            String deptCode = SecurityUtils.getLoginUser().getSysUser().getDeptCode();
            //店铺编码+班组编码+时间段月份+时间段序号
            entity.setCode(createPanDianDataDTO.getPandianCode());
            //entity.setCode(deptCode+createPanDianDataDTO.getDeptCode()+createPanDianDataDTO.getMouthDay()+createPanDianDataDTO.getSeq());
            entity.setStapAmout(t.getStapAmout());
            entity.setStapName(t.getStapName());
            entity.setStapCode(t.getStapCode());
            entity.setDeptCode(createPanDianDataDTO.getDeptCode());
            if (t.getSemiType().equals(1)){
                List<BomListVo> maps = pandianDataMapper.selectBomLists(Long.parseLong(t.getStapCode()));
                if (!CollectionUtils.isEmpty(maps)){
                    List<PandianDataEntity> aa = maps.stream().map(l->{
                        PandianDataEntity b = new PandianDataEntity();
                        b.setPid(Long.parseLong(createPanDianDataDTO.getPid()));
                        b.setCaseId(Long.parseLong(createPanDianDataDTO.getCaseId()));
                        b.setDel(0);
                        b.setCreator(SecurityUtils.getUserId());
                        b.setCreateBy(SecurityUtils.getUsername());
                        b.setCreateTime(new Date());
                        //店铺编码+班组编码+时间段月份+时间段序号
                        b.setCode(createPanDianDataDTO.getPandianCode());
                        //b.setCode(deptCode+createPanDianDataDTO.getDeptCode()+createPanDianDataDTO.getMouthDay()+createPanDianDataDTO.getSeq());
                        /*b.setStapAmout(t.getStapAmout().multiply(new BigDecimal(l.get("quota").toString())));
                        b.setStapName((String) l.get("stap_name"));
                        b.setStapCode((String) l.get("stap_code"));
                        b.setStapBaseUnit((String) l.get("unit"));*/
                        b.setStapAmout(CalculatedValueUtil.multiplyB(t.getStapAmout(),l.getQuota()));
                        b.setStapName(l.getStapName());
                        b.setStapCode(l.getStapCode());
                        b.setStapBaseUnit(l.getUnit());
                        b.setDeptCode(createPanDianDataDTO.getDeptCode());
                        String stapPrice = tqlPandianDataCaseMapper.selectStapPrice(l.getStapCode());
                        if (StringUtils.isEmpty(stapPrice)){
                            b.setStapPrice(new BigDecimal(0));
                        }else {
                            b.setStapPrice(new BigDecimal(stapPrice));
                        }
                        /******校验盘点物料是否在库存中**************/
                        StapCountBoolDTO dto = new StapCountBoolDTO();
                        dto.setNowDay(sdf.format(new Date()));
                        dto.setStapCode(l.getStapCode());
                        int count= stapInChangeService.selectStapCountBool(dto);
                        if (count>0){
                            //messageContent.append("物料："+t.getStapName()+",库存不足。");
                            messageContent.append("半成品："+t.getStapName()+"-物料"+l.getStapName().toString()+",暂无该物料库存");
                        }

                        return b;
                    }).collect(Collectors.toList());
                    list.addAll(aa);
                }
            }else {
                entity.setStapAmout(t.getStapAmout());
                entity.setStapName(t.getStapName());
                entity.setStapCode(t.getStapCode());
                entity.setStapBaseUnit(t.getStapBaseUnit());
                String stapPrice = tqlPandianDataCaseMapper.selectStapPrice(t.getStapCode());
                if (StringUtils.isEmpty(stapPrice)){
                    entity.setStapPrice(new BigDecimal(0));
                }else {
                    entity.setStapPrice(new BigDecimal(stapPrice));
                }
                list.add(entity);

                /******校验盘点物料是否在库存中**************/
                StapCountBoolDTO dto = new StapCountBoolDTO();
                dto.setNowDay(sdf.format(new Date()));
                dto.setStapCode(t.getStapCode());
                int count=  stapInChangeService.selectStapCountBool(dto);
                if (count>0){
                    messageContent.append("物料："+t.getStapName()+",暂无该库存。");
                }
            }
        });
        if (messageContent.toString().length() > 0){
            log.info("校验物料信息：{}",messageContent);
            //发出一个监听事件
            applicationContext.publishEvent(new LogEvent(dataLog));
            dataLog.setDataContent("修改盘点单失败，"+messageContent.toString());
            tqlPandianDataLogMapper.insert(dataLog);
            return ResultDTO.success(0,500,"修改盘点单失败："+messageContent.toString());
        }

        //先删除，在修改
        int a = pandianDataMapper.deleteDataByIds(createPanDianDataDTO.getIds());
        /************操作tql_pandian_data_case (办成品未打散)*************/
        if (createPanDianDataDTO.getDataCaseIds().size() > 0){
            int v = tqlPandianDataCaseMapper.deleteCaseDataByIds(createPanDianDataDTO.getDataCaseIds());
        }

        //再插入
        tqlPandianDataCaseMapper.batchPanDianDataCaseInsert(dataCaseList);
        int r= pandianDataMapper.batchInsertPanDianData(list);
        tqlPandianDataLogMapper.insert(dataLog);
        return ResultDTO.success(r,200,"修改盘点单成功！");
    }


}
